package com.action.mvc.ssh.controller;

import com.action.mvc.ssh.entity.Person;
import com.action.mvc.ssh.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * Created by Wuxiang on 2017/4/9.
 *
 * 访问： http://localhost:8080/person/main
 */
@Controller
@RequestMapping("/person")
public class PersonController {
    @Autowired
    private PersonService personService;

    @RequestMapping("/main")
    public String main(Model model) {
        List<Person> personList = personService.getPersons();
        for (int i = 0; i < personList.size(); i++) {
            System.out.println(personList.get(i).toString());
        }
        model.addAttribute("personList", personList);
        return "main";
    }

    @RequestMapping("/addPrompt")
    public String addPrompt() {
        return "savepage";
    }

    @RequestMapping("/add")
    public String addPerson(Person person) {
        personService.addPerson(person);
        return "redirect:main";
    }

    @RequestMapping("/updatePrompt")
    public String updatePrompt(@RequestParam String id,Model model) {
        model.addAttribute("person", personService.getPersonById(id));
        return "editpage";
    }

    @RequestMapping("/update")
    public String updatePerson(Person person) {
        personService.updatePerson(person);
        return "redirect:main";
    }

    @RequestMapping("/delete")
    public String deletePersonById(@RequestParam String id) {
        personService.deletePersonById(id);
        return "redirect:main";
    }
}
